package beer.xz.beer.device.data.channel

import android.content.Context
import android.util.Log
import beer.xz.beer.device.data.api.ApiConfig
import beer.xz.beer.device.data.api.Apis
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken


data class Product(
    val uid: String, val name: String, val imageUrl: String, val remark: String?
)

data class Channel(
    val uid: String, val name: String, val index: Int, val productId: String
)

object Channels {
    private val channels: MutableList<Channel> = mutableListOf()
    private fun setChannels(channels: List<Channel>) {
        this.channels.clear()
        this.channels.addAll(channels)
    }

    fun getChannels(): List<Channel> {
        return channels.toList()
    }

    fun save(context: Context) {
        val gson = Gson()
        val json = gson.toJson(channels)
        val file = context.getFileStreamPath("channels.json")
        file.outputStream().bufferedWriter().use { writer ->
            writer.write(json)
        }
    }

    fun hasChannels(): Boolean {
        return channels.isNotEmpty()
    }


    suspend fun load(context: Context): Boolean {
        var result = false
        try {
            val file = context.getFileStreamPath("channels.json")
            //for test
            file.delete()
            if (file.exists()) {
                Log.d("load", "channels.json found,load from file")
                val json = file.inputStream().bufferedReader().use { it.readText() }
                val typeToken = object : TypeToken<List<Channel>>() {}.type
                val tmpList = Gson().fromJson<List<Channel>>(json, typeToken)
                this.channels.clear()
                this.channels.addAll(tmpList)
                result = true
            } else {
                Log.d("load", "channels.json not found,load from server")
                val resultChannels = Apis.ChannelService.getChannels(ApiConfig.getCode()!!)
                if (resultChannels.success) {
                    resultChannels.data?.let {
                        if (it.isNotEmpty()) {
                            setChannels(it.sortedBy { channel: Channel -> channel.index })
                            save(context)
                            result = true
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("load", "load channels failed", e)
        }
        return result
    }

    fun removeFile(context: Context) {
        val file = context.getFileStreamPath("channels.json")
        file.delete()
    }

}